package authorized

import (
	"fmt"
	"time"
	"net/http"
	"math/rand"
	"github.com/xinliangnote/go-gin-api/internal/code"
	"github.com/xinliangnote/go-gin-api/internal/pkg/core"
)
type authSendVerifyCodeRequest struct {
	PhoneNumber string `uri:"phone_number" binding:"required"` // 需要加密的字符串
}

type authResponse struct {
	Code int `json:"code"` // 返回码
	Message string `json:"message"`
}


func (h *handler) SendVerifyCode() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(authSendVerifyCodeRequest)
		res := new(authResponse)

		if err := ctx.ShouldBindURI(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				code.Text(code.ParamBindError)).WithError(err),
			)
			return
		}
		rand.Seed(time.Now().UnixNano())
		vcode := fmt.Sprintf("%04d", rand.Intn(10000))
		_, err := h.service.SendLoginVerifyCode(req.PhoneNumber, vcode)
		if err != nil{
			res.Message =  err.Error()
			res.Code = 400
		}else{
			res.Code = 200
			res.Message = "发送短信到" + req.PhoneNumber + "成功"
		}
		ctx.Payload(res)
	}
}
